package org.csu.awesome.util;

/**
 * @author csucoderlee
 * @version 1.0, Nov 23, 2018
 */
public class ByteUtil {

    /**
     * Returns a new byte array between start and end index.
     *
     *
     * @param bytes
     *          to be splited
     *          被分割的数组
     * @param start
     *          the start index, inclusive.
     *          起始位置，包含该位置
     * @param end
     *          the end index, inclusive.
     *          结束位置，包含该位置
     * @return
     */
    public static byte[] split(byte[] bytes, int start, int end) {

        if (null == bytes) {
            return null;
        }

        if (start < 0) {
            throw new IllegalArgumentException("start < 0");
        }

        if (end > bytes.length) {
            throw new IllegalArgumentException("end > bytes.length");
        }

        int len = end - start + 1;

        byte[] dest = new byte[len];
        System.arraycopy(bytes, start, dest, 0, len);
        return dest;
    }

    /**
     * reverse src byte array
     * 给定一个byte数组，翻转返回新数组
     * @param bytes
     *          to be reversed
     *          被反转的数组
     * @return
     */
    public static byte[] reverse(byte[] bytes) {
        if (null == bytes) {
            return null;
        }

        byte[] dest = new byte[bytes.length];
        int j = 0;
        for (int i = bytes.length - 1; i >= 0; i--) {
            dest[j] = bytes[i];
            j++;
        }

        return dest;
    }

    /**
     * return the target first occurence in the source byte array.
     * 返回目标字节在字节数组第一次出现的数组下标
     * @param source
     * @param target
     * @return  if occurs, return the index of the first byte; if it does not occur, <code>-1</code> is returned.
     */
    public static int indexOf(byte[] source, byte target) {
        if (null == source || source.length == 0) {
            return -1;
        }
        for (int i = 0; i < source.length; i++) {
            if (source[i] == target) {
                return i;
            }
        }
        return -1;
    }

    /**
     * 返回16进制
     * @param bytes
     * @param separator
     * @return
     */
    public static String asHex(byte[] bytes, String separator) {
        StringBuilder sb = new StringBuilder();
        return sb.toString();
    }

    public static void main(String[] args) {
        byte[] bytes = {1, 2, 3, 4, 5};
        System.out.println(split(bytes, 1, 2).length);
        byte[] dest;
        for (int i = 0; i < (dest = reverse(bytes)).length; i++) {
            System.out.println(dest[i]);
        }

        byte i = 2;
        System.out.println(indexOf(bytes, i));
    }
}
